package com.example.demo2.config;

import cn.hutool.json.JSONUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.example.demo2.common.Result;
import com.example.demo2.entity.Customer;
import com.example.demo2.entity.DTO.FieldCustomerDTO;
import com.example.demo2.exception.ServiceException;
import com.example.demo2.service.CustomerService;

import java.util.ArrayList;
import java.util.List;


public class ExcelHeadDataListener extends AnalysisEventListener<FieldCustomerDTO> {
    private CustomerService customerService;

    public ExcelHeadDataListener(CustomerService customerService) {
        this.customerService = customerService;
    }

    List<Customer> list = new ArrayList<>();

    @Override
    public void invoke(FieldCustomerDTO fieldCustomerDTO, AnalysisContext analysisContext) {
        Customer customer = new Customer();
        customer.setUsername(fieldCustomerDTO.get用户名());
        customer.setNickname(fieldCustomerDTO.get昵称());
        customer.setSex(fieldCustomerDTO.get性别());
        customer.setPassword(fieldCustomerDTO.get密码());
        customer.setPhone(fieldCustomerDTO.get手机());
        list.add(customer);
    }
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        try {
            customerService.saveBatch(list);
        } catch (Exception e) {
            throw new ServiceException("-1", JSONUtil.toJsonStr(e));
        }
    }
}
